from flask import request
from flask_restful import Resource, reqparse
from flask_shop import models, db
from flask_shop.category import cate_api, attr_api


class Categories(Resource):

    def get(self):
        level = request.args.get('level')
        pnum = request.args.get('pnum')
        psize = request.args.get('psize')
        if level:
            level = int(level)
        else:
            level = 3
        base_categories = models.Category.query.filter(models.Category.level == 1)
        if all([pnum, psize]):
            categories = base_categories.paginate(page=int(pnum), per_page=int(psize))
        else:
            categories = base_categories.all()
        categories_list = self.to_tree(categories, level)
        # for c in categories:
        #     first_dict = c.to_dict()
        #     # 获取一级分类下的二级分类
        #     first_dict['children'] = []
        #     for sc in c.children:
        #         second_dict = sc.to_dict()
        #         second_dict['children'] = []
        #         # 获取三级分类:
        #         for tc in sc.children:
        #             second_dict['children'].append(tc.to_dict())
        #         first_dict['children'].append(second_dict)
        #     categories_list.append(first_dict)
        return {'status': 200, 'msg': '获取分类成功', 'data': categories_list}

    def to_tree(self, info: list, level):
        info_list = []
        # 遍历分类
        for i in info:
            i_dict = i.to_dict()
            if i.level < level:
                i_dict['children'] = self.to_tree(i.children, level)
            info_list.append(i_dict)
        return info_list

    def post(self):
        try:
            # 创建requestParse对象
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument('name', type=str, required=True)
            parser.add_argument('level', type=int, required=True)
            parser.add_argument('pid', type=int)
            # 解析数据
            args = parser.parse_args()
            # 判断参数
            if args.get('pid'):
                c = models.Category(name=args.get('name'), level=args.get('level'), pid=args.get('pid'))
            else:
                c = models.Category(name=args.get('name'), level=args.get('level'))
            db.session.add(c)
            db.session.commit()
            return {'status': 200, 'msg': '添加分类成功'}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '添加分类失败 '}


cate_api.add_resource(Categories, '/')


class Attributes(Resource):

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('_type', type=str, required=True, location='args')
        parser.add_argument('cid', type=int, required=True, location='args')
        args = parser.parse_args()
        # 根据cid获取分类信息
        cate = models.Category.query.get(args.get('cid'))
        # 获取分类下的所有属性信息
        attr_list = []
        # attrs = cate.attrs
        # 根据_type获取对象的属性
        if args.get('_type') == 'static':
            attr_list = [a.to_dict() for a in cate.attrs if a._type == 'static']
        elif args.get('_type') == 'dynamic':
            attr_list = [a.to_dict() for a in cate.attrs if a._type == 'dynamic']

        return {'status': 200, 'msg': '获取属性成功', 'data': attr_list}

    def post(self):
        try:
            # 创建RequestParse对象
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument('name', type=str, required=True)
            parser.add_argument('val', type=str)
            parser.add_argument('_type', type=str, required=True)
            parser.add_argument('cid', type=int, required=True)
            # 解析参数
            args = parser.parse_args()
            # 判断val
            if args.get('val'):
                c = models.Attribute(name=args.get('name'), val=args.get('val'),
                                     _type=args.get('_type'), cid=args.get('cid'))
            else:
                c = models.Attribute(name=args.get('name'), _type=args.get('_type'), cid=args.get('cid'))
            db.session.add(c)
            db.session.commit()
            return {'status': 200, 'msg': '添加属性成功'}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '添加属性失败'}


attr_api.add_resource(Attributes, "/attributes/")


class Attribute(Resource):
    def get(self, id):
        try:
            attr = models.Attribute.query.get(id)
            return {'status': 200, 'msg': '获取属性成功', 'data': attr.to_dict()}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '获取属性失败'}

    def put(self, id):
        try:
            attr = models.Attribute.query.get(id)
            parser = reqparse.RequestParser()
            # 添加参数
            parser.add_argument('name', type=str)
            parser.add_argument('val', type=str)
            parser.add_argument('_type', type=str)
            parser.add_argument('cid', type=int)
            args = parser.parse_args()
            if args.get('name'):
                attr.name = args.get('name')
            if args.get('val'):
                attr.val = args.get('val')
            if args.get('_type'):
                attr._type = args.get('_type')
            if args.get('cid'):
                attr.cid = args.get('cid')
            db.session.commit()
            return {'status': 200, 'msg': '修改属性成功'}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '修改属性失败'}

    def delete(self, id):
        try:
            attr = models.Attribute.query.get(id)
            db.session.delete(attr)
            db.session.commit()
            return {'status': 200, 'msg': '删除属性成功'}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '删除属性失败'}


attr_api.add_resource(Attribute, "/attribute/<int:id>/")
